﻿using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using RemoteTool.Common;
using RemoteTool.Server.ViewModels;
using RemoteToolData.Data;
using X.PagedList;

namespace RemoteTool.Server.Controllers
{
    public class DeviceController : Controller
    {
        private readonly ILogger<DeviceController> logger;
        private readonly ApplicationDbContext applicationDbContext;

        public DeviceController(ILogger<DeviceController> logger, ApplicationDbContext applicationDbContext)
        {
            this.logger = logger;
            this.applicationDbContext = applicationDbContext;
        }
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Create()
        {
            return View();
        }

        public async Task<IActionResult> Delete(string guidCode)
        {
            var info = new DeviceInfo();

            if (guidCode == null)
            {
                info = applicationDbContext.DeviceInfos.Where(p => string.IsNullOrEmpty(p.GuidCode)).FirstOrDefault();
            }
            else
            {
                info = applicationDbContext.DeviceInfos.Where(p => p.GuidCode == guidCode).FirstOrDefault();
            }
            if (info == null)
            {
                ViewBag.ErrorMsg = $"找不到guidCode={guidCode}的设备";
                return View("~/Views/Error/Error.cshtml");
            }
            else
            {
                if (User?.Identity?.Name == info.CreatorName || User?.Identity?.Name == "lixing")
                {
                    applicationDbContext.DeviceInfos.Remove(info);
                    applicationDbContext.SaveChanges();
                }
                else
                {
                    ViewBag.ErrorMsg = $"设备创建者为{info.CreatorName}不是当前用户,无法进行删除！";
                    return View("~/Views/Error/Error.cshtml");
                }
            }

            try
            {
                var list = await applicationDbContext.DeviceInfos.ToListAsync();
                if (list?.Count > 0)
                {
                    SortedDictionary<string, DeviceInfo> dictionary = new SortedDictionary<string, DeviceInfo>();
                    foreach (var item in list)
                    {
                        if (dictionary.ContainsKey(item.ProjectName) == false)
                            dictionary.Add(item.ProjectName, item);
                    }

                    ViewBag.OperaMsg = $"总共查询到{list.Count}条结果，包含项目{dictionary.Keys.Count}个！";
                    var infos = list.ToPagedList<DeviceInfo>(1, HomeController.PageSize);
                    return RedirectToAction("index", "home", infos);
                }
                else
                {
                    ViewBag.OperaMsg = $"当前没有设备信息记录！";
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"查询设备信息发生异常->{ex.Message}");
            }
            return View();
        }

        public IActionResult Details(string guidCode)
        {
            var info = applicationDbContext.DeviceInfos.Where(p => p.GuidCode == guidCode).FirstOrDefault();
            var mode = info?.Adapt<DeviceInfoViewModel>();
            if (mode == null)
            {
                ViewBag.ErrorMsg = $"找不到guidCode={guidCode}的设备";
                return View("~/Views/Error/Error.cshtml");
            }
            else
            { return View(mode); }
        }

        public IActionResult Modify(string guidCode)
        {
            var info = applicationDbContext.DeviceInfos.Where(p => p.GuidCode == guidCode).FirstOrDefault();
            var mode = info?.Adapt<DeviceInfoViewModel>();
            if (mode == null)
            {
                ViewBag.ErrorMsg = $"找不到guidCode={guidCode}的设备";
                return View("~/Views/Error/Error.cshtml");
            }
            else
            { return View(mode); }
        }

        [HttpPost]
        public async Task<IActionResult> Save(DeviceInfoViewModel model)
        {
            if (ModelState.IsValid)
            {
                var info = new DeviceInfo();
                model.GuidCode = Guid.NewGuid().ToString("N");
                model.CreatorName = User.Identities.FirstOrDefault()?.Name;
                model.CreateTime = DateTime.Now;
                info.CopyObjValue<DeviceInfo>(model);
                applicationDbContext.Add(info);
                applicationDbContext.SaveChanges();
            }
            try
            {
                var list = await applicationDbContext.DeviceInfos.ToListAsync();
                if (list?.Count > 0)
                {
                    SortedDictionary<string, DeviceInfo> dictionary = new SortedDictionary<string, DeviceInfo>();
                    foreach (var item in list)
                    {
                        if (dictionary.ContainsKey(item.ProjectName) == false)
                            dictionary.Add(item.ProjectName, item);
                    }
                    //homeModel.DeviceCount = list.Count;
                    //homeModel.ProjectCount = dictionary.Keys.Count;
                    //homeModel.OperaMsg = $"总共查询到{list.Count}条结果，包含项目{dictionary.Keys.Count}个！";
                    //homeModel.DeviceInfos = await list.ToPagedListAsync(1, 10);
                    //homeModel.PageNumber = 1;
                    //homeModel.PageCount = homeModel.DeviceInfos.PageCount;

                    ViewBag.OperaMsg = $"总共查询到{list.Count}条结果，包含项目{dictionary.Keys.Count}个！";
                    var infos = list.ToPagedList<DeviceInfo>(1, HomeController.PageSize);
                    return RedirectToAction("index", "home", infos);
                }
                else
                {
                    ViewBag.OperaMsg = $"当前没有设备信息记录！";
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"查询设备信息发生异常->{ex.Message}");
            }
            return View();

        }

        [HttpPost]
        public async Task<IActionResult> Modify(DeviceInfoViewModel model)
        {
            var info = applicationDbContext.DeviceInfos.Where(p => p.GuidCode == model.GuidCode).FirstOrDefault();
            if (info == null)
            {
                ViewBag.ErrorMsg = $"找不到guidCode={model.GuidCode}的设备";
                return View("~/Views/Error/Error.cshtml");
            }
            else
            {
                info.ProjectName = model.ProjectName;
                info.DeviceName = model.DeviceName;
                info.DeviceSerialNo = model.DeviceSerialNo;
                info.OraySunId = model.OraySunId;
                info.OraySunPsw = model.OraySunPsw;
                info.ToDeskId = model.ToDeskId;
                info.ToDeskPsw = model.ToDeskPsw;
                applicationDbContext.SaveChanges();

            }

            try
            {
                var list = await applicationDbContext.DeviceInfos.ToListAsync();
                if (list?.Count > 0)
                {
                    SortedDictionary<string, DeviceInfo> dictionary = new SortedDictionary<string, DeviceInfo>();
                    foreach (var item in list)
                    {
                        if (dictionary.ContainsKey(item.ProjectName) == false)
                            dictionary.Add(item.ProjectName, item);
                    }
                    ViewBag.OperaMsg = $"总共查询到{list.Count}条结果，包含项目{dictionary.Keys.Count}个！";
                    var infos = list.ToPagedList<DeviceInfo>(1, HomeController.PageSize);
                    return RedirectToAction("index", "home", infos);
                }
                else
                {
                    ViewBag.OperaMsg = $"当前没有设备信息记录！";
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"查询设备信息发生异常->{ex.Message}");
            }
            return View();
        }
    }
}
